/* eslint-disable max-len */
const { Service } = require('egg')
const cheerio = require('cheerio')
const { encryptPassword } = require('../utils/AES')

module.exports = class LoginService extends Service {
  /**
   * * 模拟登录，获取cookie
   * @return {setCookie: string, status: number} **
   */
  async getCookie() {
    try {
      const { ctx } = this
      const { sid, pwd } = ctx.data
      // 1.请求门户网站
      const apiUrl = `${ctx.state.baseUrl}/authserver/login?service=http%3A%2F%2Fcsujwc.its.csu.edu.cn%2Fsso.jsp`
      const res = await ctx.curl(apiUrl, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
      })
      // console.log((res.data.toString()));
      const pwdEncryptSalt = /id="pwdEncryptSalt" value="(.*?)"/.exec(res.data.toString())[1]
      // const pwdEncryptSalt = pwdEncryptSaltarr[1];
      // console.log('pwdEncryptSalt', pwdEncryptSalt);
      const $ = cheerio.load(res.data.toString())
      const hiddenFields = {
        lt: '', dllt: '', execution: '', _eventId: '', captcha: '', cllt: '',
      }
      const hiddenKeys = Object.keys(hiddenFields)
      hiddenKeys.forEach((e) => {
        hiddenFields[e] = $(`input[name="${e}"]`).val()
      })
      let setCookie = res.headers['set-cookie'] ? res.headers['set-cookie'].map((e) => e.split(';')[0]).join(';') : ''
      // console.log('setCookie', setCookie);
      const encryptedData = encryptPassword(pwd, pwdEncryptSalt)
      // console.log('encryptedData', encryptedData);
      // 2.请求登录
      const RedirectRes = `${ctx.state.baseUrl}/authserver/login?service=http%3A%2F%2Fcsujwc.its.csu.edu.cn%2Fsso.jsp`
      const res2 = await ctx.curl(RedirectRes, {
        method: 'POST',
        data: {
          username: sid,
          password: encryptedData,
          captcha: '',
          _eventId: 'submit',
          cllt: '',
          dllt: '',
          lt: '',
          execution: hiddenFields.execution,
        },
        headers: {
          Cookie: setCookie,
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
      })
      // console.log('res2.data.toString()', res2);

      // 3.重定向1
      const RedirectRes1 = await ctx.curl(res2.headers.location, {
        method: 'GET',
        headers: {
          Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
          'Accept-Encoding': 'gzip, deflate, br, zstd',
          'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
          'Upgrade-Insecure-Requests': '1',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
        },
      })
      // console.log('RedirectRes1', RedirectRes1.status);
      const setCookiearr = RedirectRes1.headers['set-cookie'] ? RedirectRes1.headers['set-cookie'].map((e) => e.split(';')[0]) : ''
      setCookie = `${setCookiearr[0]};${setCookiearr[1]}`
      // console.log('setCookie', setCookie);

      // 4.重定向2
      const RedirectRes2 = await ctx.curl(RedirectRes1.headers.location, {
        method: 'GET',
        headers: {
          Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
          'Accept-Encoding': 'gzip, deflate, br, zstd',
          'Accept-Language': 'zh-CN,zh;q=0.9',
          'Cache-Control': 'max-age=0',
          Cookie: setCookie,
          'Upgrade-Insecure-Requests': '1',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
        },
      })
      // console.log('RedirectRes2.status', RedirectRes2.status);

      // 5.重定向3
      const RedirectRes3 = await ctx.curl(RedirectRes2.headers.location, {
        method: 'GET',
        headers: {
          Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
          'Accept-Encoding': 'gzip, deflate, br, zstd',
          'Accept-Language': 'zh-CN,zh;q=0.9',
          'Cache-Control': 'max-age=0',
          Cookie: setCookie,
          'Upgrade-Insecure-Requests': '1',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
        },
      })
      console.log('RedirectRes3.status', RedirectRes3.status)
      return { setCookie, status: res2.status }
    } catch (err) {
      // console.log(err);
      return { setCookie: '', status: 500 }
    }
  }
}
